<template>
  <div>
    <h2>待办清单</h2>
    <div class="container todo-container">
      <div class="input-container">
        <select v-model="selectedCategoryKey" class="category-select">
          <option v-for="category in categoryList" :key="category.key" :value="category.key">{{ category.name }}</option>
        </select>
        <input v-model="newTodo" placeholder="添加新的内容" class="todo-input" />
        <button @click="addTodo" class="add-button">添加</button>
      </div>
      <ul class="todo-list">
        <li v-for="category in categoryList" :key="category.key">
          <h3 class="category-heading">{{ category.name }}</h3>
          <ul>
            <li v-for="(todo, index) in categorizedTodoList[category.key]" :key="index" class="todo-item">
              <span class="todo-text" @dblclick="editTodo(category.key, index)">
                <span v-if="!editingTodoKeys.includes(category.key + '-' + index)">{{ todo }}</span>
                <input v-else type="text" v-model="tempTodoText[category.key + '-' + index]" />
              </span>
              <button @click="removeTodo(category.key, index)" class="remove-button">删除</button>
              <button v-if="editingTodoKeys.includes(category.key + '-' + index)" @click="saveEdit(category.key, index)" class="save-button">保存</button>
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { openDB } from 'idb';

const categorizedTodoList = ref({});
const newTodo = ref('');
const selectedCategoryKey = ref('shopping');
const categoryList = ref([
  { key: 'shopping', name: '待购清单' },
  { key: 'execute', name: '待办事项' },
]);

// 追踪当前正在编辑的待办事项的键
const editingTodoKeys = ref([]);
// 临时存储正在编辑的待办事项文本
const tempTodoText = ref({});

const openDatabase = async () => {
  return await openDB('todo-db', 1, {
    upgrade(db) {
      db.createObjectStore('categorizedTodoList', { keyPath: 'id', autoIncrement: true });
    }
  });
};

const loadTodoList = async () => {
  const db = await openDatabase();
  const tx = db.transaction('categorizedTodoList', 'readonly');
  const store = tx.objectStore('categorizedTodoList');
  const allTodoList = await store.getAll();
  categorizedTodoList.value = allTodoList.reduce((acc, item) => {
    acc[item.categoryKey] = item.todoList.map(todo => todo.text);
    return acc;
  }, {});
};

const saveTodo = async () => {
  const db = await openDatabase();
  const tx = db.transaction('categorizedTodoList', 'readwrite');
  const store = tx.objectStore('categorizedTodoList');
  const currentData = Object.entries(categorizedTodoList.value).map(([categoryKey, todoList]) => ({
    categoryKey,
    todoList: todoList.map((text, index) => ({ id: index + 1, text }))
  }));
  await store.clear();
  currentData.forEach(data => store.put(data));
  await tx.done;
};

onMounted(() => {
  loadTodoList();
});

const addTodo = () => {
  if (newTodo.value) {
    if (!categorizedTodoList.value[selectedCategoryKey.value]) {
      categorizedTodoList.value[selectedCategoryKey.value] = [];
    }
    categorizedTodoList.value[selectedCategoryKey.value].push(newTodo.value);
    newTodo.value = '';
    saveTodo();
  }
};

const removeTodo = (categoryKey, index) => {
  categorizedTodoList.value[categoryKey].splice(index, 1);
  saveTodo();
};

const editTodo = (categoryKey, index) => {
  const key = categoryKey + '-' + index;
  editingTodoKeys.value = [...editingTodoKeys.value, key];
  tempTodoText.value[key] = categorizedTodoList.value[categoryKey][index];
};

const saveEdit = (categoryKey, index) => {
  const key = categoryKey + '-' + index;
  const newText = tempTodoText.value[key];
  categorizedTodoList.value[categoryKey][index] = newText;
  editingTodoKeys.value = editingTodoKeys.value.filter(k => k !== key);
  delete tempTodoText.value[key];
  saveTodo();
};
</script>

<style lang="scss" scoped>
@use "../assets/common.scss";

.todo-container {
  width: 400px;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.todo-heading {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.category-select {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.input-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.todo-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.add-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.add-button:hover {
  background-color: #0056b3;
}

.todo-list {
  list-style-type: none;
  padding: 0;
}

.category-heading {
  margin-bottom: 10px;
  color: #666;
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ccc;
}

.todo-text {
  flex: 1;
  cursor: pointer;
}

.todo-text input {
  width: 100%;
  box-sizing: border-box;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.remove-button {
  padding: 5px 10px;
  border: none;
  border-radius: 5px;
  background-color: #dc3545;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.remove-button:hover {
  background-color: #c82333;
}

.save-button {
  padding: 5px 10px;
  border: none;
  border-radius: 5px;
  background-color: #28a745;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-left: 10px;
}

.save-button:hover {
  background-color: #218838;
}
</style>